package itcast.shops.web;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import itcast.domain.CarBean;
import itcast.domain.PageBean;
import itcast.domain.User;
import itcast.service.ShopsService;
import itcast.service.ShopsServiceimpl;

/**
 * 查询购物车对象存储car转发到购物车页面上
 */
@WebServlet("/carshopindexServlet")
public class CarshopindexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * 购物车实现对象
     */
    public CarshopindexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			//1、设置编码
				request.setCharacterEncoding("utf-8");//解决保存文件乱码问题
				response.setCharacterEncoding("utf-8");//解决保存文件乱码问题
			//2、获取用户名id
				String userid=request.getParameter("userid"); 
			//3、利用userid去查询购物车对象
		    //4、调用service去查询购物车对象
				ShopsService service=new ShopsServiceimpl();
				List<CarBean> car=service.findcarshop(userid);
                float totalprices=0;//商品总价格
				int sum=0;//商品总件数
				for (CarBean carBean : car) {
					sum+=carBean.getCounts();
					
					totalprices+=carBean.getPrices()*carBean.getCounts();
					
					carBean.setTotalcount(sum);
				}
				//第二种方法
//				for(int i=0; i <car.size()-1;i++){  //循环设置DepId的值
//					CarBean  CB=(CarBean)(car.get(i)); //获取对当前对象的引用
//					  CB.setDepId(depId); //操作该对象；等进入下次循环，该引用会指向下一个对象，然后对其操作；
//					} 
//				
				//商品小计
//				for (CarBean carBean : car) {
//					float i= carBean.getPrices()*carBean.getCounts();
//					carBean.setSubtotal(i);
//				}
				
				
			//5、存储car转发到购物车页面上
				request.setAttribute("cars", car);
				request.setAttribute("totalsum",sum);//商品总件数
				request.setAttribute("totalprices",totalprices);//商品总价格
				request.getRequestDispatcher("carshops.jsp").forward(request, response);
	}

}
